package com.example.statistics.utils.file

import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.provider.MediaStore
import com.example.statistics.bean.DocumentBean
import com.example.statistics.bean.FolderBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.util.*

object DocumentLoading {
    private val queryUri = MediaStore.Files.getContentUri("external")
    private val orderBy = MediaStore.Files.FileColumns.DATE_MODIFIED

    // 媒体文件数据库字段
    private val projection = arrayOf(
            MediaStore.Files.FileColumns._ID,
            MediaStore.MediaColumns.DATA,
            MediaStore.MediaColumns.MIME_TYPE,
            MediaStore.Files.FileColumns.SIZE,
            MediaStore.MediaColumns.DATE_MODIFIED)
    private val selection = "(" +
            MediaStore.Files.FileColumns.DATA + " LIKE '%.xls'" +
            " or " + MediaStore.Files.FileColumns.DATA + " LIKE '%.xlsx'" +
            " or " + MediaStore.Files.FileColumns.DATA + " LIKE '%.doc'" +
            " or " + MediaStore.Files.FileColumns.DATA + " LIKE '%.docx'" +
//            " or " + MediaStore.Files.FileColumns.DATA + " LIKE '%.ppt'" +
//            " or " + MediaStore.Files.FileColumns.DATA + " LIKE '%.pptx'" +
            " or " + MediaStore.Files.FileColumns.DATA + " LIKE '%.pdf'" + ")"

    suspend fun query(context: Context, body: (List<FolderBean>) -> Unit) {
        withContext(Dispatchers.IO) {
            var cursor: Cursor? = null
            return@withContext try {
//                context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file:///storage/emulated/0/Tencent")))
//                context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file:///storage/emulated/0/DingTalk")))
//                context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file:///storage/emulated/0/jianke")))
                context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file:///storage/emulated/0")))
                cursor = context.contentResolver.query(queryUri, projection, selection, null, orderBy)
                val folderList = ArrayList<FolderBean>()
                val documentList = ArrayList<DocumentBean>()
                return@withContext cursor?.let {
                    if (it.count > 0) {
                        var id = 1
                        it.moveToLast()
                        do {
                            val path = it.getString(it.getColumnIndexOrThrow(projection[1]))
                            val mineType = it.getString(it.getColumnIndexOrThrow(projection[2]))
                            val size = it.getLong(it.getColumnIndexOrThrow(projection[3]))
                            val time = it.getLong(it.getColumnIndexOrThrow(projection[4]))
                            val mark = path.hashCode()
                            val documentBean = DocumentBean(id, path, duration = time, mimeType = mineType, size = size, mark = mark)
                            folder(documentBean, folderList)
                            documentList.add(documentBean)
                            id++
                        } while (it.moveToPrevious())
                        if (!documentList.isNullOrEmpty()) {
                            val folderBean = FolderBean()
                            folderBean.name = "全部"
                            folderBean.documentList = documentList
                            folderList.add(0, folderBean)
                        }
                    }
                    withContext(Dispatchers.Main) {
                        body(folderList)
                    }
                }

            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                cursor?.close()
            }
        }
    }

    /**
     * 文件分类
     *
     * @param path
     * @param folderList
     * @return
     */
    private fun folder(media: DocumentBean, folderList: MutableList<FolderBean>) {
        val imageFile = File(media.path)
        val folderName = imageFile.parentFile.absolutePath.toLowerCase(Locale.getDefault())
        val newFolderName = when {
            folderName.contains("tencent") -> "腾讯"
            folderName.contains("weixin") -> "微信"
            folderName.contains("dingtalk") -> "钉钉"
            else -> return
        }
        // 同一个文件夹下，返回自己，否则创建新文件夹
        folderList.forEach {
            if (it.name == newFolderName) {
                it.documentList.add(media)
                return
            }
        }
        val newFolder = FolderBean()
        newFolder.name = newFolderName
        newFolder.path = imageFile.parentFile.absolutePath
        newFolder.documentList.add(media)
        folderList.add(newFolder)
    }
}
